package com.example.gobang.game;

import com.example.gobang.model.User;
import com.example.gobang.model.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.UUID;

@Component
@Data
public class Room {
    @Autowired
    private onlineUserManager onlineUserManager1;
    @Autowired
    private RoomManger roomManger;
    @Autowired
    private UserMapper userMapper;
    private static final int MAX_ROW = 15;
    private static final int MAX_COL = 15;
    private String roomId;
    private User user1;
    private User user2;
    private int whiteUser;
    private int[][] borard = new int[15][15];

    public Room() {
        roomId = UUID.randomUUID().toString();
    }

    public void putChess(String reqJson) throws IOException {
        System.out.println("数据：" + reqJson);
        GameRequst gameRequst = new ObjectMapper().readValue(reqJson, GameRequst.class);
        GameReponse reponse = new GameReponse();

        // 检查 user1 和 user2 是否为 null，防止空指针异常
        if (user1 == null || user2 == null) {
            System.out.println("错误：房间中的用户信息不完整，user1 或 user2 为 null");
            return;
        }

        int chess = gameRequst.getUserId() == user1.getUserId() ? 1 : 2;
        int row = gameRequst.getRow();
        int col = gameRequst.getCol();
        if (borard[row][col] != 0) {
            System.out.println("当前位置：" + "行：" + row + "," + "列：" + col);
            return;
        }
        borard[row][col] = chess;
        printBoard();
        int winner = checkWinner(row, col, chess);
        System.out.println("[Room.putChess] winner=" + winner);
        reponse.setMessage("putChess");
        reponse.setUserId(gameRequst.getUserId());
        reponse.setRow(row);
        reponse.setCol(col);
        reponse.setWinner(winner);
        System.out.println("onlineUserManager1"+onlineUserManager1);
        WebSocketSession session1 = onlineUserManager1.getFromGameRoom(user1.getUserId());
        WebSocketSession session2 = onlineUserManager1.getFromGameRoom(user2.getUserId());
        // 只有在没有胜负结果时，才因为玩家离线而判定胜负
        if (reponse.getWinner() == 0) {
            if (session1 == null && session2 != null) {
                // 记录玩家一下线，但不立即判定胜负
                System.out.println("玩家一下线");
            } else if (session2 == null && session1 != null) {
                // 记录玩家二下线，但不立即判定胜负
                System.out.println("玩家二下线");
            } else if (session1 == null && session2 == null) {
                // 两个玩家都离线，游戏结束但无胜负
                System.out.println("两个玩家都离线");
            }
        }
        String respJson = new ObjectMapper().writeValueAsString(reponse);
        if (session1 != null) {
            session1.sendMessage(new TextMessage(respJson));
        }
        if (session2 != null) {
            session2.sendMessage(new TextMessage(respJson));
        }
        if (reponse.getWinner() != 0) {

            System.out.println("游戏结束！房间即将销毁！roomId=" + roomId + " 获胜方为：" + reponse.getWinner());
            // 更新获胜方和失败方的信息。

            int winUserId = reponse.getWinner();
            int loseUserId = reponse.getWinner() == user1.getUserId() ? user2.getUserId() : user1.getUserId();
            userMapper.useWin(winUserId);
            userMapper.userLose(loseUserId);
            // 销毁房间

            roomManger.remove(roomId, user1.getUserId(), user2.getUserId());


        }
    }

    private void printBoard() {
        // 打印出棋盘

        System.out.println("[打印棋盘信息] " + roomId);
        System.out.println("=====================================================================");
        for (int r = 0; r < MAX_ROW; r++) {
            for (int c = 0; c < MAX_COL; c++) {
                // 针对一行之内的若干列，不要打印换行

                System.out.print(borard[r][c] + " ");
            }
            // 每次遍历完一行之后，再打印换行。

            System.out.println();
        }
        System.out.println("=====================================================================");
    }

    private int checkWinner(int row, int col, int chess) {
        // 1. 检查所有的行
        for (int c = col - 4; c <= col; c++) {
            // 确保索引在有效范围内
            if (c < 0 || c + 4 >= MAX_COL) {
                continue;
            }

            // 检查五个连续位置是否都是当前玩家的棋子
            boolean win = true;
            for (int i = 0; i < 5; i++) {
                if (borard[row][c + i] != chess) {
                    win = false;
                    break;
                }
            }

            if (win) {
                // 构成了五子连珠！胜负已分！
                return chess == 1 ? user1.getUserId() : user2.getUserId();
            }
        }

        // 2. 检查所有列
        for (int r = row - 4; r <= row; r++) {
            // 确保索引在有效范围内
            if (r < 0 || r + 4 >= MAX_ROW) {
                continue;
            }

            // 检查五个连续位置是否都是当前玩家的棋子
            boolean win = true;
            for (int i = 0; i < 5; i++) {
                if (borard[r + i][col] != chess) {
                    win = false;
                    break;
                }
            }

            if (win) {
                return chess == 1 ? user1.getUserId() : user2.getUserId();
            }
        }

        // 3. 检查左对角线（从左上到右下）
        for (int r = row - 4, c = col - 4; r <= row && c <= col; r++, c++) {
            // 确保索引在有效范围内
            if (r < 0 || r + 4 >= MAX_ROW || c < 0 || c + 4 >= MAX_COL) {
                continue;
            }

            // 检查五个连续位置是否都是当前玩家的棋子
            boolean win = true;
            for (int i = 0; i < 5; i++) {
                if (borard[r + i][c + i] != chess) {
                    win = false;
                    break;
                }
            }

            if (win) {
                return chess == 1 ? user1.getUserId() : user2.getUserId();
            }
        }

        // 4. 检查右对角线（从右上到左下）
        for (int r = row - 4, c = col + 4; r <= row && c >= col; r++, c--) {
            // 确保索引在有效范围内
            if (r < 0 || r + 4 >= MAX_ROW || c - 4 < 0 || c >= MAX_COL) {
                continue;
            }

            // 检查五个连续位置是否都是当前玩家的棋子
            boolean win = true;
            for (int i = 0; i < 5; i++) {
                if (borard[r + i][c - i] != chess) {
                    win = false;
                    break;
                }
            }

            if (win) {
                return chess == 1 ? user1.getUserId() : user2.getUserId();
            }
        }

        // 胜负未分，就直接返回 0
        return 0;
    }

}
